iT邦幫忙

2026 iThome 鐵人賽

DAY 7
0
Software Development

我是Java工程師,關於密碼學我想懂的不多系列 第 7

Day06 - 現代密碼學基礎 -- XOR 運算與可逆性

  • 分享至 

  • xImage
  •  

一、 二進位 (Binary)

電腦的世界本質上是由 01 構成的高低電位訊號。我們在螢幕上看到的文字、圖片或加密後的密文,在底層運算時都只是一連串的二進位資料:

  • 位元 (bit):電腦最小的資料單位,數值非 0 即 1。
  • 位元組 (byte):電腦處理資料的基本單位,$1\text{ byte} = 8\text{ bits}$(例如 01000001 代表 ASCII 碼中的字元 'A')。

二、 位元邏輯運算:XOR(互斥或)

在電腦的二進位邏輯運算中(如 AND、OR、NOT 等),XOR(Exclusive OR,互斥或) 扮演了密碼學中最核心的角色。它的數學符號記作 $\oplus$。

XOR 的運算規則非常簡單直覺:「相同為 0,不同為 1」
https://ithelp.ithome.com.tw/upload/images/20260921/20128084Vhz8r2VePp.png

三、 為什麼密碼學特別鍾愛 XOR?

XOR 具備一項完美的數學特性——可逆性(Reversibility)。當我們對同一組資料用相同的金鑰進行兩次 XOR 運算時,資料就會還原回原本的樣子:

  • 加密(Encryption):明文 ⊕ 金鑰 = 密文
  • 解密(Decryption):密文 ⊕ 金鑰 = 明文
    https://ithelp.ithome.com.tw/upload/images/20260921/201280846pCE5GednI.png

四、 Java 中如何實作 XOR 運算?

在 Java 語言中,XOR 運算主要分為以下三種常見層次:

1. 基本型別的 XOR 運算(原生 ^ 運算子)

Java 對所有整數型別(byte, short, char, int, long)都支援 ^ 位元運算子。

public static void main( String[] args ) throws CharacterCodingException {
    int a = 5;  // 二進位: 0101
    int b = 3;  // 二進位: 0011
    System.out.println("a:"+toBinary4(a));
    System.out.println("b:"+toBinary4(b));
    int c = a ^ b; // 二進位: 0110 -> 10 進位的 6
    System.out.println("a ^ b:"+toBinary4(c));

    // 驗證可逆性
    int restored = c ^ b; // 6 ^ 3 -> 0110 ^ 0011 = 0101 (5)
    System.out.println("c ^ b:"+toBinary4(restored));

}
public static String toBinary4(int value) {
    int low4 = value & 0xFF;
    return String.format("%4s", Integer.toBinaryString(low4)).replace(' ', '0');
}

2. 密碼學實務:位元組陣列 (byte[]) 的 XOR 加解密

在密碼學中,我們處理的資料(明文、密文、金鑰)都是二進位的 byte[]。由於 Java 的位元運算子會在運算時自動將 byte 提升(Promotion)為 int**,因此在將結果賦值回 byte 時,必須進行強制型別轉換 (Type Cast)**。

/**
 * 對輸入的 byte 陣列與 Key 進行逐位元 XOR 運算
 */
public static byte[] xorProcess(byte[] input, byte[] key) {
    byte[] result = new byte[input.length];

    for (int i = 0; i < input.length; i++) {
        // 注意:(byte) 強制轉型不可或缺,因為 ^ 運算會自動轉成 int
        result[i] = (byte) (input[i] ^ key[i % key.length]);
    }

    return result;
}

3. 大數的 XOR 運算 (java.math.BigInteger)

在非對稱密碼學(如 RSA、ECC)或高維度演算法中,我們經常需要處理幾百個 Bytes 的超大數字。Java 的 BigInteger 提供了內建的 .xor() 方法:

import java.math.BigInteger;

public class BigIntegerXorDemo {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("123456789012345678901234567890");
        BigInteger num2 = new BigInteger("987654321098765432109876543210");

        // 大數 XOR 運算
        BigInteger xorResult = num1.xor(num2);
      
        // 驗證還原
        BigInteger restoredNum1 = xorResult.xor(num2);

        System.out.println("XOR 結果: " + xorResult);
        System.out.println("還原驗證: " + restoredNum1.equals(num1)); // true
    }
}

Reference

  • 世界第一簡單密碼學 - 三谷政昭、佐藤伸一

上一篇
Day05 - 現代密碼學基礎 -- Base64與Hex Code
下一篇
Day07 - 現代密碼學基礎 -- 亂數產生器 (RNG)
系列文
我是Java工程師,關於密碼學我想懂的不多8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言